package com.jeesite.modules.home.service;

import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.home.dao.DcProvinceMajorDao;
import com.jeesite.modules.home.entity.DcProvinceMajor;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.utils.ExcelUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @description:
 * @author: ciye
 * @date: 2022/3/14 16:48
 */
@Service
@Transactional(readOnly=false)
@RequiredArgsConstructor
public class DcProvinceMajorService extends CrudService<DcProvinceMajorDao, DcProvinceMajor> {

    private final DcProvinceMajorDao dcProvinceMajorDao;

    /**
     * 查询主要经济指标排名
     * @param publishYearMonth
     * @param cityName
     * @return
     */
    public Map getProvinceMajorRank(String publishYearMonth, String cityName){
        Map map = new HashMap();

        if (StringUtils.isBlank(cityName)) {
            cityName = "芜湖市";
        }

        DcProvinceMajor provinceMajor = new DcProvinceMajor();
        // 获取数据
        if (StringUtils.isEmpty(publishYearMonth)) {
            String latest = dcProvinceMajorDao.getLatestYearMonth();
            provinceMajor = dcProvinceMajorDao.getProvinceMajorRank(latest, cityName);
        } else {
            // 返回用户查询的数据
            provinceMajor = dcProvinceMajorDao.getProvinceMajorRank(publishYearMonth, cityName);
        }
        // 处理数据
        if(provinceMajor != null){
            // 定义接收集合
            List<String> xAxisData = new ArrayList();
            List<Integer> seriesData = new ArrayList();
            List<Integer> tooltipData = new ArrayList();
            // 拼装返回结果
            xAxisData.add("地区生产总值");
            tooltipData.add(provinceMajor.getGdpValue3());
            xAxisData.add("第一产业");
            tooltipData.add(provinceMajor.getPrimaryIndustryValue3());
            xAxisData.add("第二产业");
            tooltipData.add(provinceMajor.getSecondaryIndustryValue3());
            xAxisData.add("第三产业");
            tooltipData.add(provinceMajor.getTertiaryIndustryValue3());
            xAxisData.add("一产比重");
            tooltipData.add(provinceMajor.getPrimaryIndustryRank());
            xAxisData.add("二产比重");
            tooltipData.add(provinceMajor.getSecondaryIndustryRank());
            xAxisData.add("三产比重");
            tooltipData.add(provinceMajor.getTertiaryIndustryRank());
            xAxisData.add("规模以上工业增加值");
            tooltipData.add(provinceMajor.getAboveScaleIndustryIncreaseValue2());
            xAxisData.add("战略性新兴产业产值");
            tooltipData.add(provinceMajor.getStrategicEmergingIndustriesValue2());
            xAxisData.add("高新产业增加值");
            tooltipData.add(provinceMajor.getHighTechIndustryValue2());
            xAxisData.add("固定资产投资");
            tooltipData.add(provinceMajor.getFixedAssetsInvestValue2());
            xAxisData.add("技改投资");
            tooltipData.add(provinceMajor.getTechUpgradeInvestValue2());
            xAxisData.add("房地产投资");
            tooltipData.add(provinceMajor.getRealEstateInvestValue2());
            xAxisData.add("民间投资");
            tooltipData.add(provinceMajor.getPrivateInvestValue2());
            xAxisData.add("全社会消费品零售额");
            tooltipData.add(provinceMajor.getWholeSocietyConsumerGoodsValue3());
            xAxisData.add("一般公共预算收入");
            tooltipData.add(provinceMajor.getGeneralPublicBudgetRevenueValue3());
            xAxisData.add("金融机构人民币各项存款");
            tooltipData.add(provinceMajor.getFinancialInstitutionsRmbDepositsValue3());
            xAxisData.add("金融机构人民币各项贷款");
            tooltipData.add(provinceMajor.getFinancialInstitutionsRmbLoansValue3());
            xAxisData.add("商品房销售面积");
            tooltipData.add(provinceMajor.getCommercialHouseSaleAreaValue3());
            xAxisData.add("建筑业总产值");
            tooltipData.add(provinceMajor.getBuildingIndustryTotalOutputValue3());
            xAxisData.add("全社会用电量");
            tooltipData.add(provinceMajor.getTotalElectricityConsumptionValue3());
            xAxisData.add("工业用电量");
            tooltipData.add(provinceMajor.getIndustrialPowerConsumptionValue3());
            xAxisData.add("进出口总额");
            tooltipData.add(provinceMajor.getTotalExportImportVolumeValue3());
            xAxisData.add("城乡居民人均可支配收入");
            tooltipData.add(provinceMajor.getPerCapitaDisposableIncomeValue2());
            xAxisData.add("城镇常住居民人均可支配收入");
            tooltipData.add(provinceMajor.getUrbanPerCapitaDisposableIncomeValue2());
            xAxisData.add("农村常住居民人均可支配收入");
            tooltipData.add(provinceMajor.getRuralPerCapitaDisposableIncomeValue2());

            // 处理柱状图展示高度问题
            Integer tempInt = 0;
            // 获取最大值
            for (Integer item : tooltipData) {
                if (item > tempInt){
                    tempInt = item;
                }
            }
            // 加一，保证最小值至少为1
            tempInt+=1;
            // 倒序解决高度问题
            for (Integer item : tooltipData) {
                seriesData.add(tempInt - item);
            }

            map.put("xAxisData",xAxisData);
            map.put("seriesData",seriesData);
            map.put("tooltipData",tooltipData);
        }

        return map;
    }

    /**
     * 获取经济指标数据
     * @param publishYearMonth
     * @return
     */
    public List<DcProvinceMajor> getProvinceMajor(String publishYearMonth) {
        List<DcProvinceMajor> provinceMajors = new ArrayList<>();
        // 获取数据
        if (StringUtils.isEmpty(publishYearMonth)) {
            String latest = dcProvinceMajorDao.getLatestYearMonth();
            provinceMajors = dcProvinceMajorDao.getProvinceMajor(latest);
        } else {
            // 返回用户查询的数据
            provinceMajors = dcProvinceMajorDao.getProvinceMajor(publishYearMonth);
        }
        return provinceMajors;
    }

    /**
     * 导入数据
     * @param file
     * @param updateFlag
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String infoImport(MultipartFile file, String updateFlag) {
        try{
            // 读取excel中的数据到集合中
            InputStream inputStream = file.getInputStream();
            List<List<String>> list = ExcelUtils.readExcel(file.getOriginalFilename(), inputStream);

            // 校验excel格式
            if (!checkExcelData(list)) {
                return "没有读取到正确的Excel导入信息！";
            }

            // 定义统计年月和编印日期
            String tempStatisticsYearMonth = "";
            String tempYm = "";

            // 获取统计年月和编印日期
            if (list.get(3) != null && StringUtils.isNotBlank(list.get(3).get(0))) {
                tempStatisticsYearMonth = list.get(3).get(0);
            }
            if (list.get(4) != null && StringUtils.isNotBlank(list.get(4).get(6))) {
                // 处理编印日期样式
                tempYm = getTransTime(list.get(4).get(6).substring(5).replace("年", "-").replace("月", "-").replace("日", ""));
            }

            // updateFlag为0，表示新增，需要查重；为1表示替换，需要先删除再添加
            if ("0".equals(updateFlag)) {
                // 判断数据库中是否有数据
                String tempCheckRepeat = dcProvinceMajorDao.checkRepeat(tempYm);
                if (StringUtils.isNotBlank(tempCheckRepeat)) {
                    // 通过编印日期删除数据
                    dcProvinceMajorDao.deleteByYearMonth(tempYm);
                    // 获取需要存储的数据
                    List<DcProvinceMajor> provinceMajorList = getProvinceMajor(tempStatisticsYearMonth, tempYm, list);
                    saveProvinceMajor(provinceMajorList);
                    return "数据导入成功，已更新原始数据！";
                } else {
                    // 获取需要存储的数据
                    List<DcProvinceMajor> provinceMajorList = getProvinceMajor(tempStatisticsYearMonth, tempYm, list);
                    saveProvinceMajor(provinceMajorList);
                    return "数据导入成功！";
                }
            } else if ("1".equals(updateFlag)) {
                // 通过编印日期删除数据
                dcProvinceMajorDao.deleteByYearMonth(tempYm);
                // 获取需要存储的数据
                List<DcProvinceMajor> provinceMajorList = getProvinceMajor(tempStatisticsYearMonth, tempYm, list);
                saveProvinceMajor(provinceMajorList);
                return "数据导入成功，已更新原始数据！";
            } else {
                return"参数错误！";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "系统异常，请联系管理员！";
        }
    }

    /**
     * 检查excel数据格式是否正确
     * @param list
     * @return
     */
    public Boolean checkExcelData(List<List<String>> list) {
        Boolean flag = true;
        // 检查文件是否有值
        if (list == null || list.size() == 0 || list.size() != 204) {
            flag = false;
        }
        // 检查文件的值是否正确
        if (list.get(2) == null || !"全省主要经济指标快报".equals(list.get(2).get(0))) {
            flag = false;
        }
        if (list.get(7) == null || !"全省".equals(list.get(7).get(0).replaceAll("\\s*", ""))) {
            flag = false;
        }
        return flag;
    }

    /**
     * 将字符串转日期，月份补0
     * @param timeStr
     * @return
     */
    public String getTransTime(String timeStr) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-M-dd");
        LocalDate date = LocalDate.parse(timeStr, df);
        DateTimeFormatter f2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String transTime = f2.format(date);
        return transTime.substring(0, 7);
    }

    /**
     * 将String转换为BigDecimal
     * @param str
     * @return
     */
    public BigDecimal checkBigDecimalValue(String str) {
        if (StringUtils.isBlank(str) || "#N/A".equals(str)) {
            return null;
        } else {
            return new BigDecimal(str);
        }
    }

    /**
     * 将String转换为Integer
     * @param str
     * @return
     */
    public Integer checkIntegerValue(String str) {
        if (StringUtils.isBlank(str) || "#N/A".equals(str)) {
            return null;
        } else {
            return Integer.valueOf(str);
        }
    }

    /**
     * 获取经济指标实体的集合
     * @param tempStatisticsYearMonth
     * @param tempYm
     * @param list
     * @return
     */
    public List<DcProvinceMajor> getProvinceMajor(String tempStatisticsYearMonth, String tempYm, List<List<String>> list) {
        // 获取当前时间
        Date tempCurrentDate = new Date();
        // 记录需要存储的数据
        List<DcProvinceMajor> provinceMajorList = new ArrayList<>();
        // 遍历集合，获取各地区指标值
        for (int i = 7; i < 24; i++) {
            // 标记累加次数
            int tempI = 0;

            // 定义实体接收数据
            DcProvinceMajor provinceMajor = new DcProvinceMajor();
            provinceMajor.setStatisticsYearMonth(tempStatisticsYearMonth);
            provinceMajor.setPublishYearMonth(tempYm);
            provinceMajor.setCreateBy(UserUtils.getUser().getUserCode());
            provinceMajor.setCreateDate(tempCurrentDate);

            // 获取各类型指标数值
            for (int j = i; tempI < 10; j += 20) {
                // 累加标记值
                tempI += 1;
                // 遍历当前行
                for (int k = 0; k < list.get(j).size(); k++) {
                    if (tempI == 1) {
                        // 第1张表
                        provinceMajor.setCityName(list.get(j).get(0));
                        provinceMajor.setGdpValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setGdpValue2(checkBigDecimalValue(list.get(j).get(2)));
                        provinceMajor.setGdpValue3(checkIntegerValue(list.get(j).get(3)));
                        provinceMajor.setGdpValue4(checkBigDecimalValue(list.get(j).get(4)));
                        provinceMajor.setGdpValue5(checkIntegerValue(list.get(j).get(5)));
                        provinceMajor.setPrimaryIndustryValue1(checkBigDecimalValue(list.get(j).get(6)));
                        provinceMajor.setPrimaryIndustryValue2(checkBigDecimalValue(list.get(j).get(7)));
                        provinceMajor.setPrimaryIndustryValue3(checkIntegerValue(list.get(j).get(8)));
                        provinceMajor.setPrimaryIndustryValue4(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setPrimaryIndustryValue5(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 2) {
                        // 第2张表
                        provinceMajor.setSecondaryIndustryValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setSecondaryIndustryValue2(checkBigDecimalValue(list.get(j).get(2)));
                        provinceMajor.setSecondaryIndustryValue3(checkIntegerValue(list.get(j).get(3)));
                        provinceMajor.setSecondaryIndustryValue4(checkBigDecimalValue(list.get(j).get(4)));
                        provinceMajor.setSecondaryIndustryValue5(checkIntegerValue(list.get(j).get(5)));
                        provinceMajor.setTertiaryIndustryValue1(checkBigDecimalValue(list.get(j).get(6)));
                        provinceMajor.setTertiaryIndustryValue2(checkBigDecimalValue(list.get(j).get(7)));
                        provinceMajor.setTertiaryIndustryValue3(checkIntegerValue(list.get(j).get(8)));
                        provinceMajor.setTertiaryIndustryValue4(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setTertiaryIndustryValue5(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 3) {
                        // 第3张表
                        provinceMajor.setPrimaryIndustryWeight(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setPrimaryIndustryRank(checkIntegerValue(list.get(j).get(2)));
                        provinceMajor.setSecondaryIndustryWeight(checkBigDecimalValue(list.get(j).get(3)));
                        provinceMajor.setSecondaryIndustryRank(checkIntegerValue(list.get(j).get(4)));
                        provinceMajor.setTertiaryIndustryWeight(checkBigDecimalValue(list.get(j).get(5)));
                        provinceMajor.setTertiaryIndustryRank(checkIntegerValue(list.get(j).get(6)));
                        provinceMajor.setAboveScaleIndustryIncreaseValue1(checkBigDecimalValue(list.get(j).get(7)));
                        provinceMajor.setAboveScaleIndustryIncreaseValue2(checkIntegerValue(list.get(j).get(8)));
                        provinceMajor.setStrategicEmergingIndustriesValue1(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setStrategicEmergingIndustriesValue2(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 4) {
                        // 第4张表
                        provinceMajor.setHighTechIndustryValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setHighTechIndustryValue2(checkIntegerValue(list.get(j).get(2)));
                        provinceMajor.setFixedAssetsInvestValue1(checkBigDecimalValue(list.get(j).get(3)));
                        provinceMajor.setFixedAssetsInvestValue2(checkIntegerValue(list.get(j).get(4)));
                        provinceMajor.setTechUpgradeInvestValue1(checkBigDecimalValue(list.get(j).get(5)));
                        provinceMajor.setTechUpgradeInvestValue2(checkIntegerValue(list.get(j).get(6)));
                        provinceMajor.setRealEstateInvestValue1(checkBigDecimalValue(list.get(j).get(7)));
                        provinceMajor.setRealEstateInvestValue2(checkIntegerValue(list.get(j).get(8)));
                        provinceMajor.setPrivateInvestValue1(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setPrivateInvestValue2(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 5) {
                        // 第5张表
                        provinceMajor.setWholeSocietyConsumerGoodsValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setWholeSocietyConsumerGoodsValue2(checkBigDecimalValue(list.get(j).get(2)));
                        provinceMajor.setWholeSocietyConsumerGoodsValue3(checkIntegerValue(list.get(j).get(3)));
                        provinceMajor.setWholeSocietyConsumerGoodsValue4(checkBigDecimalValue(list.get(j).get(4)));
                        provinceMajor.setWholeSocietyConsumerGoodsValue5(checkIntegerValue(list.get(j).get(5)));
                        provinceMajor.setGeneralPublicBudgetRevenueValue1(checkBigDecimalValue(list.get(j).get(6)));
                        provinceMajor.setGeneralPublicBudgetRevenueValue2(checkBigDecimalValue(list.get(j).get(7)));
                        provinceMajor.setGeneralPublicBudgetRevenueValue3(checkIntegerValue(list.get(j).get(8)));
                        provinceMajor.setGeneralPublicBudgetRevenueValue4(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setGeneralPublicBudgetRevenueValue5(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 6) {
                        // 第6张表
                        provinceMajor.setFinancialInstitutionsRmbDepositsValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setFinancialInstitutionsRmbDepositsValue2(checkBigDecimalValue(list.get(j).get(2)));
                        provinceMajor.setFinancialInstitutionsRmbDepositsValue3(checkIntegerValue(list.get(j).get(3)));
                        provinceMajor.setFinancialInstitutionsRmbDepositsValue4(checkBigDecimalValue(list.get(j).get(4)));
                        provinceMajor.setFinancialInstitutionsRmbDepositsValue5(checkIntegerValue(list.get(j).get(5)));
                        provinceMajor.setFinancialInstitutionsRmbLoansValue1(checkBigDecimalValue(list.get(j).get(6)));
                        provinceMajor.setFinancialInstitutionsRmbLoansValue2(checkBigDecimalValue(list.get(j).get(7)));
                        provinceMajor.setFinancialInstitutionsRmbLoansValue3(checkIntegerValue(list.get(j).get(8)));
                        provinceMajor.setFinancialInstitutionsRmbLoansValue4(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setFinancialInstitutionsRmbLoansValue5(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 7) {
                        // 第7张表
                        provinceMajor.setCommercialHouseSaleAreaValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setCommercialHouseSaleAreaValue2(checkBigDecimalValue(list.get(j).get(2)));
                        provinceMajor.setCommercialHouseSaleAreaValue3(checkIntegerValue(list.get(j).get(3)));
                        provinceMajor.setCommercialHouseSaleAreaValue4(checkBigDecimalValue(list.get(j).get(4)));
                        provinceMajor.setCommercialHouseSaleAreaValue5(checkIntegerValue(list.get(j).get(5)));
                        provinceMajor.setBuildingIndustryTotalOutputValue1(checkBigDecimalValue(list.get(j).get(6)));
                        provinceMajor.setBuildingIndustryTotalOutputValue2(checkBigDecimalValue(list.get(j).get(7)));
                        provinceMajor.setBuildingIndustryTotalOutputValue3(checkIntegerValue(list.get(j).get(8)));
                        provinceMajor.setBuildingIndustryTotalOutputValue4(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setBuildingIndustryTotalOutputValue5(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 8) {
                        // 第8张表
                        provinceMajor.setTotalElectricityConsumptionValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setTotalElectricityConsumptionValue2(checkBigDecimalValue(list.get(j).get(2)));
                        provinceMajor.setTotalElectricityConsumptionValue3(checkIntegerValue(list.get(j).get(3)));
                        provinceMajor.setTotalElectricityConsumptionValue4(checkBigDecimalValue(list.get(j).get(4)));
                        provinceMajor.setTotalElectricityConsumptionValue5(checkIntegerValue(list.get(j).get(5)));
                        provinceMajor.setIndustrialPowerConsumptionValue1(checkBigDecimalValue(list.get(j).get(6)));
                        provinceMajor.setIndustrialPowerConsumptionValue2(checkBigDecimalValue(list.get(j).get(7)));
                        provinceMajor.setIndustrialPowerConsumptionValue3(checkIntegerValue(list.get(j).get(8)));
                        provinceMajor.setIndustrialPowerConsumptionValue4(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setIndustrialPowerConsumptionValue5(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 9) {
                        // 第9张表
                        provinceMajor.setTotalExportImportVolumeValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setTotalExportImportVolumeValue2(checkBigDecimalValue(list.get(j).get(2)));
                        provinceMajor.setTotalExportImportVolumeValue3(checkIntegerValue(list.get(j).get(3)));
                        provinceMajor.setTotalExportImportVolumeValue4(checkBigDecimalValue(list.get(j).get(4)));
                        provinceMajor.setTotalExportImportVolumeValue5(checkIntegerValue(list.get(j).get(5)));
                        provinceMajor.setPerCapitaDisposableIncomeValue1(checkBigDecimalValue(list.get(j).get(6)));
                        provinceMajor.setPerCapitaDisposableIncomeValue2(checkIntegerValue(list.get(j).get(7)));
                        provinceMajor.setPerCapitaDisposableIncomeValue3(checkBigDecimalValue(list.get(j).get(8)));
                        provinceMajor.setPerCapitaDisposableIncomeValue4(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setPerCapitaDisposableIncomeValue5(checkIntegerValue(list.get(j).get(10)));
                    } else if (tempI == 10) {
                        // 第10张表
                        provinceMajor.setUrbanPerCapitaDisposableIncomeValue1(checkBigDecimalValue(list.get(j).get(1)));
                        provinceMajor.setUrbanPerCapitaDisposableIncomeValue2(checkIntegerValue(list.get(j).get(2)));
                        provinceMajor.setUrbanPerCapitaDisposableIncomeValue3(checkBigDecimalValue(list.get(j).get(3)));
                        provinceMajor.setUrbanPerCapitaDisposableIncomeValue4(checkBigDecimalValue(list.get(j).get(4)));
                        provinceMajor.setUrbanPerCapitaDisposableIncomeValue5(checkIntegerValue(list.get(j).get(5)));
                        provinceMajor.setRuralPerCapitaDisposableIncomeValue1(checkBigDecimalValue(list.get(j).get(6)));
                        provinceMajor.setRuralPerCapitaDisposableIncomeValue2(checkIntegerValue(list.get(j).get(7)));
                        provinceMajor.setRuralPerCapitaDisposableIncomeValue3(checkBigDecimalValue(list.get(j).get(8)));
                        provinceMajor.setRuralPerCapitaDisposableIncomeValue4(checkBigDecimalValue(list.get(j).get(9)));
                        provinceMajor.setRuralPerCapitaDisposableIncomeValue5(checkIntegerValue(list.get(j).get(10)));
                    }
                }
            }
            provinceMajorList.add(provinceMajor);
        }
        return provinceMajorList;
    }

    /**
     * 存储经济指标数据
     * @param provinceMajorList
     */
    public void saveProvinceMajor(List<DcProvinceMajor> provinceMajorList) {
        for (DcProvinceMajor item : provinceMajorList) {
            dcProvinceMajorDao.insert(item);
        }
    }

    public String getDate() {
        return dao.getDate();
    }
}
